package com.example.demo.controller.user;

import com.example.demo.service.user.IUserService;
import com.example.demo.utils.DifyClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxProcessor;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    private static FluxProcessor<String, String> processor;
    @Value("${dify.api_key}")
    private static String apiKey;
    /**
     * 上传照片做查询
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/load",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Set<? extends Map.Entry<String, ?>> load(@RequestBody MultipartFile file) throws Exception {
        return userService.load(file);
    }

    /**
     * 根据病类查询执行方案
     * @param sickName
     * @return
     */
    @GetMapping("/executors")
    public Flux<ServerSentEvent<String>> excute(@RequestParam String sickName){
        processor= DirectProcessor.<String>create().serialize();
        new Thread(()->{
//            String apiKey = "app-OahH9s3glemmAMV0Sy0SzJRb";
            try {
                new DifyClient(apiKey).runWorkflow(sickName+"怎么治");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();
        return processor.onBackpressureBuffer()
                .map(data -> ServerSentEvent.<String>builder()
                        .data(data)
                        .build());
    }
    public void sendToClients(String data) {
        processor.onNext(data);
    }

    // 服务端主动结束流（正常完成）
    public void stopStream() {
        processor.onComplete(); // 所有客户端收到 "close" 事件
//        System.out.println("结束");
    }
}
